export default {
	namespaced: true,

	state: () => ({
		cart: JSON.parse(uni.getStorageSync('cart') || '[]')
	}),

	mutations: {
		addToCart(state, goods) {
			const findResult = state.cart.find(item => item.goods_id == goods.goods_id)
			if (!findResult) {
				state.cart.push(goods)
			} else {
				findResult.goods_count++
			}
			this.commit('cart/saveToStorage')
		},
		saveToStorage(state) {
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		},
		changeRadio(state, goods) {
			state.cart.forEach(item => {
				if (item.goods_id == goods.goods_id) {
					item.goods_status = goods.goods_status
				}
			})
			this.commit('cart/saveToStorage')
		},
		changeCount(state, goods) {
			state.cart.forEach(item => {
				if (item.goods_id == goods.goods_id) {
					item.goods_count = goods.goods_count
				}
			})
			this.commit('cart/saveToStorage')
		},
		deleteGoods(state, goods) {
			state.cart = state.cart.filter(item => item.goods_id !== goods.goods_id)
			this.commit('cart/saveToStorage')
		},
		updateAllGoodsStatus(state, status) {
			state.cart.forEach(item => item.goods_status = status)
			this.commit('cart/saveToStorage')
		}
	},

	getters: {
		total(state) {
			let count = 0
			state.cart.forEach(item => count += item.goods_count)
			return count
		},
		checkCount(state) {
			return state.cart.filter(item => item.goods_status).reduce((total, item) => {
				total += item.goods_count
				return total
			}, 0)
		},
		totalPrice(state) {
			return state.cart.filter(item => item.goods_status).reduce((total, item) => {
				total += item.goods_count * item.goods_price
				return total
			}, 0).toFixed(2)
		},
		isAllChecked(state) {
			return state.cart.every(item => item.goods_status)
		}
	}
}